/*
 *  AsyncBuffer.h
 *  MusicAnalyzer
 *
 *  Created by jiro on 12/03/27.
 *  Copyright 2012 jiro music. All rights reserved.
 *
 */

#pragma once

#include <vector>
#include <stack>
#include <queue>
#include "pthread.h"

#include "Buffer.h"
#include "IObserver.h"

namespace sc
{
	class AsyncBufferSystem
	{
	public:

		AsyncBufferSystem( int bufferByteCount, int bufferCount );
		
		~AsyncBufferSystem();

		void StartPolling();

		void StopPolling();

		bool AddObserver( IObserver< Buffer >& observer );

		void WriteData( const uint8_t* data, int byteCount );

		int GetBufferCount() const;

		int GetBufferByteCount() const;

	private:

		void Alloc( int bufferByteCount, int bufferCount );

		static void* ReadData( void* );		//	polling function

		static bool continuePolling;

	private:

		std::vector< IObserver< Buffer >* > observers;

		std::vector< Buffer* > buffers;					//	memorize buffer head ptr to safe delete

		std::stack< Buffer* > cleanBufferStack;

		std::queue< Buffer* > dirtyBufferQueue;

		pthread_t pollingThread;

		pthread_mutex_t mutex;

		int bufferByteCount;

		std::vector< uint8_t* > rawBufferHeadPtrs;		//	memorize buffer head ptr to safe delete

	};

}